//
//  WHttpTool.m
//  WArtMarket
//
//  Created by 武根宝 on 17/1/23.
//  Copyright © 2017年 环球巨人. All rights reserved.
//

#import "WHttpTool.h"
#import "AFNetworking.h"

@implementation WHttpTool

/**
 POST请求（接收JSON格式数据）
 
 @param URLString  请求的URL
 @param parameters 请求的参数
 @param success    请求成功的回调
 @param failure    请求失败的回调
 */
+ (void)POST:(NSString *)URLString parameters:(id)parameters success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure showProgress:(BOOL)show
{
    if (show && [WShareUtil sharedData].isShowWait) {
        [WShareUtil showWait:show frame:CGRectMake(0, 64, WSCREENH_WIDTH, WSCREENH_HEIGHT - 64)];
    }
    // 1、创建请求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer.timeoutInterval = 15;
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 2、发送请求
    [mgr POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        //        QFLog(@"%@", uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success)
        {
            if (show) {
                [WShareUtil showWait:NO frame:CGRectZero];
            }
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure)
        {

            if (show) {
                [WShareUtil showWait:NO frame:CGRectZero];
            }
            failure(error);
        }
    }];
}

/**
 POST请求（接收非JSON格式数据）
 
 @param URLString  请求的URL
 @param parameters 请求的参数
 @param success    请求成功的回调
 @param failure    请求失败的回调
 */
+ (void)POST_noJSON:(NSString *)URLString parameters:(id)parameters success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure showProgress:(BOOL)show
{

    if (show) {
        [WShareUtil showWait:show frame:CGRectMake(0, 64, WSCREENH_WIDTH, WSCREENH_HEIGHT - 64)];
    }
    // 1、创建请求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 2、发送请求
    [mgr POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        //        QFLog(@"%@", uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success)
        {
            if (show) {
                [WShareUtil showWait:NO frame:CGRectZero];
            }
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure)
        {

            if (show) {
                [WShareUtil showWait:NO frame:CGRectZero];
            }
            failure(error);
        }
    }];
}



// GET 请求
+ (void)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure showProgress:(BOOL)show{
    // 1、创建请求管理者
    if (show) {
        [WShareUtil showWait:show frame:CGRectMake(0, 64, WSCREENH_WIDTH, WSCREENH_HEIGHT - 64)];
    }
    WLog(@"%@",parameters);
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 2、发送请求
    [mgr GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        //        QFLog(@"%@", downloadProgress);

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success)
        {
            if (show) {
                [WShareUtil showWait:NO frame:CGRectZero];
            }
            success(responseObject);
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure)
        {

            if (show) {
                [WShareUtil showWait:NO frame:CGRectZero];
            }
            failure(error);
        }
    }];
}

// 字典转成JSON字符串
+(NSString *)convertToJsonData:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;

    if (!jsonData) {

        WLog(@"%@",error);

    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];

    return mutStr;
}

/*!

 * @brief 把格式化的JSON格式的字符串转换成字典

 * @param jsonString JSON格式的字符串

 * @return 返回字典

 */

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {

    if (jsonString == nil) {
        return nil;
    }

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData

                                                        options:NSJSONReadingMutableContainers

                                                          error:&err];
    if(err) {
        WLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

/*!

 * @brief 把格式化的JSON格式的字符串转换成数组

 * @param jsonString JSON格式的字符串

 * @return 返回数组

 */

+ (NSArray *)arrayWithJsonString:(NSString *)jsonString {

    if (jsonString == nil) {
        return nil;
    }

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSArray *array = [NSJSONSerialization JSONObjectWithData:jsonData
                                                     options:NSJSONReadingMutableContainers
                                                       error:&err];
    if(err) {
        WLog(@"json解析失败：%@",err);
        return nil;
    }

    return array;
}

//数组转json字符串

+ (NSString *)toReadableJSONString:(NSArray *)arr {
    NSData *data = [NSJSONSerialization dataWithJSONObject:arr
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:nil];

    if (data == nil) {
        return nil;
    }

    NSString *string = [[NSString alloc] initWithData:data
                                             encoding:NSUTF8StringEncoding];
    return string;
}


@end
